var resultset = '';
retflag = true;
(function($){

	$.fn.QGLCustomValidatorNum=function(validatestring,submit,form){
	var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Numeric Value.</li></ul><span></span></div></div>'
    
	if($(form).find(this).length>0 && submit){
$(form).find(this).each(function(i){
	
	flag=numberfieldvalidtion($(this).val());
	
	if(!flag){$(this).before(numbererrorstr);flagInc++;}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}    
	$(this).live("blur",function(){
		
	retflag=numberfieldvalidtion($(this).val());
		if (!retflag){$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});
	
	
	return retflag;
	}; 


	$.fn.QGLCustomValidatorDeciNum = function(validatestring,submit,form)
	{
		var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Numeric Value.</li></ul><span></span></div></div>'
    
	if($(form).find(this).length>0 && submit){
$(form).find(this).each(function(i){
	
	flag=decimalNumberfieldvalidtion($(this).val());
	
	if(!flag){$(this).before(numbererrorstr);flagInc++;}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}    
	$(this).live("blur",function(){
		
	retflag=decimalNumberfieldvalidtion($(this).val());
		if (!retflag){$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});
	

	return retflag;
	};

})(jQuery);


function numberfieldvalidtion(eleVal){
		var flag=true;
		if(isNaN(eleVal))
			flag = false;
		else if(eleVal % 1 != 0)
			flag = false;
		return flag;	
		}

function decimalNumberfieldvalidtion(eleVal){
 var flag = true;
 if(isNaN(eleVal))
  flag = false;
  return flag;

		}

function callAjaxToGetAgencyCodes(entityid,idField,valueReq,formId,id,linktype)
{
   if(entityid == null || $.trim(entityid).length == 0)
	   entityid = 0;
	   $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?getCodes',//name of action?name of method in action
		  dataType: 'json',
		  data: {entityUserId:entityid},
			 
		  success: function(result){
			  
				$(id).find("option").remove();


			  var codes = new Array();

			                  for(var i in result)
			                  {
			                	  var obj = {
			                			};

			                	  obj["value"] = result[i].codeName;
			                	  obj["id"] = result[i].rateItemId;
			                	  obj["initial"] =result[i].codeName;
			                	  obj["lastName"] = "";
			                	  obj["firstName"] = "";
			                	  codes.push(obj);
			                	  
			                	  $(id).append('<option value='+result[i].rateItemId+'>'+result[i].codeName+'</option>');
			                	  
			                  }

			            
			           //  console.log(codes);  
		            $(idField).quiggleJobAutoComplete(codes, valueReq, formId,1,linktype);
		    
		 },
		  error:function() { 
		
		  }
	});

}

function getRatesForReimbursment(jobId,type)
{
	
	  
	var reqVals = [];
	   $(".rateitemclass").each(function() {
		   reqVals.push($(this).attr('id'));
		});
	   var obj={
   			rateitems:new Array()
   			
   	}
   	obj["jobId"]=jobId;
	   obj["agencyId"]=$("#agencyId"+jobId).val();
		 

	  for(var k in reqVals){
		  var obj1 = {
 			};
		  obj1["rateItemId"] = $("#jobrateitemid"+reqVals[k]).val();
    	  obj.rateitems.push(obj1);
	
	  }
	  var obj1 = {
		};
	  var reqtypeid = $("#typeId"+jobId).val();
	  if(reqtypeid != null &&  $.trim(reqtypeid).length == 0 )
		  reqtypeid = 0;
	  obj1["rateItemId"] = reqtypeid;
	  obj.rateitems.push(obj1);
	
	   $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?getRatesForReimbursment',//name of action?name of method in action
		  dataType: 'json',
		  data: {data:JSON.stringify(obj),agencyId:$("#agencyId"+jobId).val(), jobId:jobId,type:type},
			 
		  success: function(result){
            	$("#servicesResInnerDiv").html("");

            	$("#servicesResInnerDiv").html(result[1]);
            	 $( "#servicesResDiv" ).dialog({
            	        height: 300,
            	        width: 700,
            	        modal: true,
            	        buttons: {
            	            "Add": function() {
            	            	
            	            	var allVals = [];
            	                $('#servicesRes-rate-item :checked').each(function() {
            	                  allVals.push($(this).val());
            	                });
            	                

            	            	for(var i in allVals){
            	            	  for(var j in result[0]){
            	            	   if(result[0][j].rateItemId == allVals[i]){  
            	            		   var str = getNewRateItemRow(result[0][j],'old');
            	            		   $('#servreimberstable > tbody:last').append(str);
            	            	   }
            	            		  
            	            	  }          		
            	            	}
            	              $( this ).dialog( "close" );
            	                
            	            },
            	            Cancel: function() {
            	                $( this ).dialog( "close" );
            	            }
            	        },
            	        close: function() {

            	        }
            	    });
            
		 },
		  error:function() { 
		
		  }
	});

}

function getUserMasterRateItems(jobId,type,codes,agencyId,build)
{
	
	   $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'rate-template.action?getUserMasterRateItems',
		  dataType: 'json',
		  data: {type:type,codes:JSON.stringify(codes),agencyId:agencyId},
			 
		  success: function(result){
            resultset = result;
			if(build)
			  buildMasterRateTableForQgl(result,type);
		 },
		  error:function() { 
		
		  }
	});

}
function buildMasterRateTableForQgl(result,type){
	$("#masterTableInnerDiv").html("");
	  var str = '';
	  str += '<fieldset>';
	  str += '<table width="100%" border="0" cellspacing="2" cellpadding="3" >';
	   /*str += '<tbody><colgroup>';
	   str += '<col width="1%">';
	  str += '<col width="10%">';
      str += '<col width="40%">';
      str += '<col width="10%">';
      str += '<col width="11%">';
      str += '<col width="9%">';
      str += '<col width="6%">';
      str += '<col width="6%">';
	  str += '</colgroup>';*/

	  str += '<tr align="left" valign="middle">';
	  str += '<th align="left" valign="middle"  width="3%">Select</th>';
	  str += '<th align="left" valign="middle" width="9%">Code</th>';
	  str += '<th align="left" valign="middle" width="43%">Description</th>';
	  str += '<th align="left" valign="middle" width="9%">Value</th>';
	  str += '<th align="left" valign="middle" width="11%">Unit</th>';
	  str += '<th align="left" valign="middle" width="11%">Per Unit</th>';
	  str += '<th align="center" valign="middle" width="6%">Reimbursable</th>';
	  str += '<th align="center" valign="middle" width="7%">Taxable</th>';
	  str += '</tr>';
		

	  for(var i=0;i<result.length;i++){
			
		  str += '<tr align="left" valign="middle">';
		
		
		  str += '<td align="left" valign="middle">';
		  if(result[i].duplicate)
		   str += '<input type="checkbox" disabled="disabled" value="'+result[i].userRateItemId+'" class="masterrateitemchecked" />';  
		  else
		   str += '<input type="checkbox" value="'+result[i].userRateItemId+'" class="masterrateitemchecked" />';
		  str += '</td>';
		  str += '<td align="left" valign="middle">';
		  str += '<input type="text" class="mastercodename" readonly="readonly" id="mastercodename'+result[i].userRateItemId+'" value="'+result[i].codeName+'" />';
		  str += '</td>';
		  str += '<td align="left" valign="middle">';
		  str += '<input type="text" class="mastercodedesc" id="mastercodedesc'+result[i].userRateItemId+'"  value="'+result[i].userRateItemDescription+'"/>';
		  str += '</td>';
		  str += '<td align="left" valign="middle">';
		  str += '<input type="text"  class="mastercodevalue" id="mastercodevalue'+result[i].userRateItemId+'"  value="0.00"/>';
		  str += '</td>';
		  str += '<td align="left" valign="middle">';

			  str +="<select onchange='changeoptions(\"mastercoderateunit"+result[i].userRateItemId+"\",\"mastercodeperunit"+result[i].userRateItemId+"\");'  id='mastercoderateunit"+result[i].userRateItemId+"'>";
		
          for(var j = 0; j< rateunits.length ; j++){
        	if(result[i].unit != rateunits[j].id)  
             str +="<option value='"+rateunits[j].id+"'>"+rateunits[j].type+"</option>";
			else
			 str +="<option value='"+rateunits[j].id+"' selected='selected'>"+rateunits[j].type+"</option>";
          }
		  str +="</select></td>";
			  str +="<td><select  id='mastercodeperunit"+result[i].userRateItemId+"' style='width:72px;'>";
			  for(var j = 0; j< rateunits.length ; j++){
					if(result[i].unit == rateunits[j].id){
						if(rateunits[j].type == "%" && (result[i].perUnit != 8)){
							   for(var k = 0 ; k < reqrtcodes.length ; k++){
								   
								   if(result[i].perUnit != reqrtcodes[k].rateItemId)  
				                     str +="<option value='"+reqrtcodes[k].rateItemId+"'>"+reqrtcodes[k].codeName+"</option>";
								   else
								     str +="<option value='"+reqrtcodes[k].rateItemId+"' selected='selected'>"+reqrtcodes[k].codeName+"</option>";
				                 }	
						}
						else{
						  if(perrateunits.length >0){
		                    for(var k = 0 ; k < perrateunits.length ; k++){
		                	  
		                   if(result[i].perUnit != perrateunits[k].id)  
		                    str +="<option value='"+perrateunits[k].id+"'>"+perrateunits[k].type+"</option>";
						   else
						    str +="<option value='"+perrateunits[k].id+"' selected='selected'>"+perrateunits[k].type+"</option>";
		                 }
						  }
		               }
					}
				  }		  
		  str +="</select></td>";
		  

		  str += '<td align="center" valign="middle">';
		  if(result[i].reimbursble)
		    str += '<input type="checkbox"  checked="true" id="reimbchk'+result[i].userRateItemId+'" />';
		  else
		    str += '<input type="checkbox" id="reimbchk'+result[i].userRateItemId+'" />';  

		  str += '</td>';
		  str += '<td align="center" valign="middle">';
		  if(result[i].taxable)
		    str += '<input type="checkbox" checked="true" id="taxablechk'+result[i].userRateItemId+'" />';
		  else
			str += '<input type="checkbox" id="taxablechk'+result[i].userRateItemId+'" />';
		  str += '</td>';
		  str += '</tr>';
		
								
		}
	  str += '	</tbody>';
	  str += '</table>';
	  str += '</fieldset>';
	  
	  $("#masterTableInnerDiv").html(str);
	  
	 
	  
	   	 $( "#masterTableDiv" ).dialog({
	   		 height: 450,
             width: 920,
 	        modal: true,
 	        buttons: {
 	            "Add": function() {
 	            	
 	            	
 	            	
 	                $('.masterrateitemchecked:checked').each(function() {
 	                	
 	                		var rateid = $(this).val();
 	                	
 	                		 var obj = {
 	             			};
 	                		obj["jobRateItem"] = true;
 	                		obj["rateItemId"] =0;
 	                		obj["codeName"] = $("#mastercodename"+rateid).val();
 	                		obj["rateItemDescription"] = $("#mastercodedesc"+rateid).val();
 	                		if(type == "reim"){
 	                		   obj["value"] = 1.00;
 	                		  obj["quantity"] = 1.00;
 	                		}
 	                		else{
 	                		   obj["value"] = 0.00;
 	                		  obj["quantity"] = 0.00;
 	                		}
 	                		 obj["reimbursable"] = $("#reimbchk"+rateid).is(":checked");
 	                		obj["rateItemValue"] = $("#mastercodevalue"+rateid).val();
 	                		obj["priceType"] = $("#mastercoderateunit"+rateid).val();
 	                		obj["unitType"] = $("#mastercodeperunit"+rateid).val();
 	                		
 	                		
 	                		obj["taxable"]  = $("#taxablechk"+rateid).is(":checked");
 	                	    var str = getNewRateItemRow(obj,'master');
	            		   $('#servreimberstable > tbody:last').append(str);
 	                
 	                	
 	                });
 	      
 	               $( this ).dialog( "close" );
 	                
 	            },
 	            Cancel: function() {
 	                $( this ).dialog( "close" );
 	            }
 	        },
 	        close: function() {

 	        }
 	    });
	   	 
	   	    if(type == 'reim'){
	    	  
	     	   $('#masterTableDiv').dialog( "option", "title", 'A/R Master Rate Table for Reimbursable Items');

	        }else{
	     	  
	     	   $('#masterTableDiv').dialog( "option", "title", 'A/R Master Rate Table for Non-Reimbursable Items');

	        }
}
function callAjaxToSaveTheNewScopistRateItemDetails(rateItemDetailsObject,id){
	
	
	 	$.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?saveRateItem',//name of action?name of method in action
		  dataType: 'json',
		  data: {rateItemDetails:JSON.stringify(rateItemDetailsObject)},
			 
		  success: function(result){	
			 
			  $('#'+id).val(result.rateItemId);
		 },
		  error:function() { 
			  
		  }
	});
	
}

function callAjaxToCheckJobIdExistance(agencyId,jobId,actulId,id){
	
	var rateItemDetails ={     
			"agencyId":agencyId,
			"jobId":jobId,
			"actId":actulId
			
	};
	
	 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?checkJobIdExistance',//name of action?name of method in action
		  dataType: 'json',
		  //data: {agencyId:agencyId,jobId:jobId},
		  data:{rateItemDetails:JSON.stringify(rateItemDetails)},
			 
		  success: function(result){
			  
			 if(result!=0){				 
				 alert("Job ID already exist.");
				 id.val('');
				 }
		    
		 },
		  error:function() { 
			  
		  }
	});
	
}

function callAjaxToCheckCcCodeExistance(agencyId,jobId,ccreqId){
	if(agencyId != null && $.trim(agencyId).length > 0 && agencyId > 0){
	 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?checkForCcCodeExistance',//name of action?name of method in action
		  dataType: 'json',
		  data: {agencyId:agencyId,jobId:jobId,ccrate:ccreqId.val()},
			 
		  success: function(result){
			  
			if(result==false)
				
				showDialog(jobId,ccreqId);
		    
		 },
		  error:function() { 
			 
		  }
	});
	}
}


function showDialog(jobId,ccreqId){

	
	
	$('#agency-cc-rate-item-form').dialog({
		width:950,
		
		buttons: {
	           "Create cc rate item": function() {
	               var bValid = true;
	              // allAgencyFields.removeClass( "ui-state-error" );

	               if ( bValid ) {
	                   
	                  /*  $( "#users tbody" ).append( "<tr>" +
	                    "<td>" + name.val() + "</td>" +
	                    "<td>" + email.val() + "</td>" +
	                    "<td>" + password.val() + "</td>" +
	                    "</tr>" );*/
	                    
	                   var block = $(this).find('.block-id').val();
	                   var agency = $('#' + block);
	               
	                   
	                   
	                   agency.find('.agency-cc-rate-item-id').val('0');                    
	                   agency.find('.agency-cc-rate-item-code').val($('#agency-cc-rate-item-code').val());
	                   agency.find('.agency-cc-rate-item-code-description').val($('#agency-cc-rate-item-code-description').val());
	                   agency.find('.agency-cc-rate-item-value').val($('#agency-cc-rate-item-value').val());
	                   agency.find('.agency-cc-rate-item-unit').val($('#agency-cc-rate-item-unit').val());
	                   agency.find('.agency-cc-rate-item-perunit').val($('#agency-cc-rate-item-perunit').val());
	                   agency.find('.agency-cc-rate-item-reimbursable').val($('#agency-cc-rate-item-reimbursable').val());
	                   agency.find('.agency-cc-rate-item-taxable').val($('#agency-cc-rate-item-taxable').val());
	                   agency.find('.agency-cc-rate-item-perunit-expedite').val($('#agency-cc-rate-item-taxable').val());
	                   
	                  // agency.find('.agency-cc-rate-item-code').focus();
                       
					 $('.scopist-date').focus();
						var perunitval = 0;
	                   if($('#agency-cc-rate-item-unit').val() == "2")
	                	   perunitval = $('#gency-cc-rate-item-perunit-expedite').val();
	                   else
	                	   perunitval = $('#agency-cc-rate-item-perunit').val();
	                	   
	                   var code = $('#agency-cc-rate-item-code').val();
						var value = $('#agency-cc-rate-item-value').val();
						var str = '';
						var eFlag = false;
						if($.trim(code) == "")
					    {
							str +='Code is Required.';
							eFlag = true;
					    }
						if($.trim(value) == "")
					   {
							str +='Value is Required.';
							eFlag = true;
					   }
					   else if(isNaN(value))
					   {
						   str +='Enter Numeric Value.';
						   eFlag = true;
					   }
					   $("#agency-cc-rate-item-formErrorMsgDiv").html(str);
					   if(eFlag)
						   return;

	                   var rateItemDetails={                    		
	                   		
	   						code:code,
	   						codeDescription:$('#agency-cc-rate-item-code-description').val(),
	   						value:value,
	   						unit:$('#agency-cc-rate-item-unit').val(),
	   						perUnit:perunitval,
	   						reimbursable:$('#agency-cc-rate-item-reimbursable').is(":checked"),
	   						taxable:$('#agency-cc-rate-item-taxable').is(":checked") ,
	   						entityUserId:$('.agency-id').val(),
	   						type:"AGENCYCC",
	   						ccval:ccreqId.val(),
	   						jobId:jobId
	   						
	                   };
	                   
	                   callAjaxToSaveTheNewScopistRateItemDetails(rateItemDetails,agency.find('.agency-cc-rate-item-id').attr("id"));

	                   $( this ).dialog( "close" );
	               }
	           },
	           Cancel: function() {
				   $('.scopist-date').focus();
	               $( this ).dialog( "close" );
	           }
	       },
	       close: function() {
//	           alert($(this).attr("id"));
	           //allAgencyFields.val( "" ).removeClass( "ui-state-error" );
			   $('.scopist-date').focus();
	       }
		
	});
	
}

$(document).ready(function(){
	 $(".hrstodoname").live("click",function(){
		   $('.selectedTask').each(function() {
			   $(this).removeClass("selectedTask");
			});
		   $(this).closest("div").addClass("selectedTask");
	   });
	$('.estimatePages').live("change",function(){

var jobId= $(this).closest(".job-table").find('.selectedjobid').val();

$("#estimatePages-form").dialog({
height: 350,
width: 600,
modal: true,
title:"MY HOURS TO PERFORM TASK",
hide: 'fold',
show: 'blind',
buttons: {

"Save":function(){
saveAdminstrativeHoursInJob(actualUserId,jobId);
},
"Cancel": function() {
$('.estimatePages').closest("div").next().find("input:visible").focus();
 
$(this).dialog('close');


}
},

});
$('.ui-icon').click(function(){
		
$('.estimatePages').closest("div").next().find("input:visible").focus();
});
callAjaxToDisplayAdminstrativeHours(actualUserId,jobId);
});

	//currentAction = 4;
	$(".reimjobrateitemprice,.mastercodevalue,.reimjobrateitemquantity,.reimjobrateitemcount").live("blur",function(){
		values=($(this).val()).split('.');
		one=values[0];
		two=values[1];
		
		var num = one;
		var one1 = num.toString();
		one1 = one1.replace(/^0+/,'');
		
		if(one=='' && two == '' ){ 
			
			var num=0;
			$(this).val(num.toFixed(2));
			return false;
		}
		
		var value1 = $.trim($(this).val());
		if(value1=='' || value1 == 0 ){ 
			
			var num=0;
			$(this).val(num.toFixed(2));
			return false;
		}
		
		var precisionflag=isNaN(one)?false:true;
		var scaleflag=isNaN(two)?false:true;
				
		if(!precisionflag){ 
			var num=0;
			$(this).val(num.toFixed(2));
		}
		else if(!scaleflag){
			var num=parseInt(one1,10).toFixed(2);
			$(this).val(num);
		}
		else if(values.length>1){
			if(!scaleflag && precisionflag)
			{
			var num=one;
			$(this).val(num.toFixed(2));
			}
			else if(scaleflag){
		   	var numaddO = one1+"."+two;
			var num=roundNumber(numaddO,2);
			
			if(!isNaN(num.toString().split(".")[1]))
			{
			var numaddO =  num.toString().split(".")[1].length==1?one1+"."+num.toString().split(".")[1]+"0":num;
			//alert(numaddO);
			$(this).val(numaddO);
			}
			else{
			var num=parseInt(numaddO,10).toFixed(2);
			$(this).val(num);
			}
			}
			
		}
				
		
	});
	function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
	}

	$('.job-action').click(function(){
		
		 isDetailAccountingChanged = true;
		 isFormFieldChanged = true;
		
	});
	
	$(".job-record-block :input").live("keypress",function() {
		
		isDetailAccountingChanged = true;
		 isFormFieldChanged = true;
	});
	
  $(".date-picker").live("click",function() {
		
		isDetailAccountingChanged = true;
		 isFormFieldChanged = true;
	});
	
  $(".addNewRowItemClass").live("click",function(){
	
	$(this).closest("#servicesreimform").find(":input[value='']:first").focus();

});

/*navigating without saving
var warnMessage = "You have unsaved changes on this page!";

    $('input:not(:button,:submit)').change(function () {
        window.onbeforeunload = function () {
		 if (warnMessage != null) return warnMessage;
        }
    });
	
    $('input:submit').click(function(e) {
        warnMessage = null;
    });


//end of navigating without saving
//tooltips work start
			/* $(".t-tip").each(function(){
				var spantag="<span class='toolTip-cust'><span class='toolTip-caption'>"+$(this).attr("title")+"</span></span>"
				//$(this).wrap("");
				$(this).before(spantag);    
				$(this).removeAttr("title");
			  });
			
			$(".t-tip").live("focusin mouseover",function(){
		      $(this).closest("div").find(".toolTip-cust .toolTip-caption").show("fast");
		    });
			
			$(".t-tip").live("focusout mouseout",function(){			
			      $(this).closest("div").find(".toolTip-cust .toolTip-caption").hide("fast");
            });
			
			$(".agency,.scopist,.proofer").hover(function(){
			$(this).find(".toolTip-cust:eq(1)").remove();
			});*/
	//tooltip work ended
	
/** HIGHLIGHT  COLUMNS **/

$(".numberVal").QGLCustomValidatorNum("number",false);
$(".numberValForDecimal").QGLCustomValidatorDeciNum("number",false);


$(".job-column").bind("focusin",function(){
var colindex=$(this).index();
var rowindex=$(this).closest(".job-row").index();
$(this).addClass("higlightclass");
var parentwin=$(".job-table:eq(0)").find(".job-row:eq("+rowindex+")").find(".job-column:eq("+colindex+")").addClass("higlightclass");
});

$(".job-column").bind("focusout",function(){
var colindex=$(this).index();
var rowindex=$(this).closest(".job-row").index();
 $(this).removeClass("higlightclass");
var parentwin=$(".job-table:eq(0)").find(".job-row:eq("+rowindex+")").find(".job-column:eq("+colindex+")").removeClass("higlightclass");
});


$(".job-record-block").live("submit",function(){

	if(retflag){
		$(".numberVal").QGLCustomValidatorNum("number",true,this);}
	if(retflag)
		$(".numberValForDecimal").QGLCustomValidatorDeciNum("number",true,this);

	flag=retflag;
		return flag;
	
});

$(".saveReceJobDtlForm").submit(function(){
	
	if(retflag){
		$(".numberVal").QGLCustomValidatorNum("number",true,this);}
	if(retflag)
		$(".numberValForDecimal").QGLCustomValidatorDeciNum("number",true,this);

	flag=retflag;
		return flag;
});

/** HIGHLIGHT END *	
	$(".expedite-rate-item-list").hide();

	$(".mandatoryfield").attr("data-validate","validate(required)");
	$(".emailval").customValidator("validate(email)");
	$(".urlinput").customValidator("validate(url)");
	$(".numberVal").customValidator("validate(price)");
		
		$("form").ketchup();**/
	//$('#agency-cc-rate-item-value').attr("pattern","^[0-9]+$");

	
	
	$(".callAjaxTGetAgencyCodes").click(function(){
		
		var entityid=$(this).closest(".job-table").find(".agency-id").val();
		var valueReq = $(this).closest(".job-table").find(".type-id");
		//callAjaxTGetAgencyCodes(entityid,$(this),valueReq,"#agency-form");
		
		var id = "#agency-rate-item-perunit-expedite";
		
		callAjaxToGetAgencyCodes(entityid,$(this),valueReq,"#agency-rate-item-form",id,'agencytypelink');
		
		
	});
	
	$(".scopist-rate-item-code").click(function(){
		
		
		var entityid = $(this).closest(".job-table").find(".scopist-id").val();
		var valueReq = $(this).closest(".job-table").find(".scopist-rate-item-id");
		
		var id="#scopist-rate-item-perunit-expedite";
		
		if( entityid != "" && valueReq !="" )
		callAjaxToGetAgencyCodes(entityid,$(this),valueReq,"#scopist-rate-item-form",id);
		
	});
	
	$(".proofer-rate-item-code").click(function(){
		
		var entityid = $(this).closest(".job-table").find(".proofer-id").val();
		var valueReq = $(this).closest(".job-table").find(".proofer-rate-item-id");
		
		var id = "#proofer-rate-item-perunit-expedite"
		
		if( entityid != "" && valueReq !="" )
		callAjaxToGetAgencyCodes(entityid,$(this),valueReq,"#agency-form1",id);
		
	});

	$(".job-id").blur(function(){
		
		var agencyId=$(this).closest("form").find('.agency-id').val();
		var jobId = $.trim($(this).closest("form").find('.job-id').val());
		
		if(jobId == "")
			$(this).closest("form").find(".job-id").val("");
			
		var jobActlId = $(this).closest("form").find(".jobId").val();	
	
		if( agencyId != "" && jobId !="" )
		callAjaxToCheckJobIdExistance(agencyId,jobId,jobActlId,$(this));
	});	
	
    $('.cc-code').blur(function(){
		
    	 if($(this).val() != null && $(this).val() != "" && $(this).val() >1){

		var agencyId = $(this).closest("form").find(".agency-id").val();	
		var jobId = $(this).closest("form").find(".jobId").val();	
		 
 		//callAjaxToCheckCcCodeExistance(agencyId,jobId,$(this));
    	 }
	});
    
    $(".scop-to > input:visible").live("focus", function(){
    
    	if($(this).closest(".job-table").find(".scopist-initial").val()=="Self"){
    		$(this).datepicker("destroy");
    		$(this).parent().removeClass("higlightclass");
    		$(this).blur();
    		if($(this).closest(".job-table").find(".proofer-initial").val()=="Self")
        		$(this).closest(".job-table").find(".witnes").focus();
    		else
    			$(this).closest(".job-table").find(".prof-to > input:visible").focus();
    		
    	}
    	else{
    		$(this).datepicker();
    	}
    		
    });
    $(".prof-to > input:visible").live("focus", function(){
    	
    	if($(this).closest(".job-table").find(".proofer-initial").val()=="Self"){
    		$(this).datepicker("destroy");
    		$(this).parent().removeClass("higlightclass");
    		$(this).blur();
    		$(this).closest(".job-table").find(".witnes").focus();
    		
    	}
    	else{
    		$(this).datepicker();
    	}
    		
    });
    
    $(".scop-from > input:visible").live("focus", function(){
        
    	if($(this).closest(".job-table").find(".scopist-initial").val()=="Self"){
    		$(this).datepicker("destroy");
    		$(this).parent().removeClass("higlightclass");
    		$(this).blur();
    		if($(this).closest(".job-table").find(".proofer-initial").val()=="Self")
        		$(this).closest(".job-table").find(".note").focus();
    		else
    			$(this).closest(".job-table").find(".prof-from > input:visible").focus();
    		
    	}
    	else{
    		$(this).datepicker();
    	}
    		
    });
    $(".prof-from > input:visible").live("focus", function(){
    	
    	if($(this).closest(".job-table").find(".proofer-initial").val()=="Self"){
    		$(this).datepicker("destroy");
    		$(this).parent().removeClass("higlightclass");
    		$(this).blur();
    		$(this).closest(".job-table").find(".note").focus();
    		
    	}
    	else{
    		$(this).datepicker();
    	}
    		
    });
    
    
    /*  $(".note").focus(function(){ 
    	
    	var curr=this;
		currentEle=this;
    	$('#notes').text($(this).val());
	
    	$('#notes-form').dialog({
    		width:374,
    		
    		buttons: {
    	           "Ok": function() {
    	        	   $('.note').val($('#notes').val());
    	        	   $( this ).dialog( "close" );
					   $(curr).closest("div").next().find("input:visible").focus();
    	             
    	           },
    	           Cancel: function() {
    	               $( this ).dialog( "close" );
					  $(curr).closest("div").next().find("input:visible").focus();
    	           }
    	     }
    	});
    	
    });
    
    $('.witnes').focus(function(){
    	var curr=this;
		currentEle=this;
    	$('#witness').text($(this).val());    	
    	
    	$('#witness-form').dialog({
    		width:374,    		
    		buttons: {
    	           "Ok": function() {
    	        	   $('.witnes').val($('#witness').val());
    	        	   $( this ).dialog( "close" );    	 
						$(curr).closest("div").next().find("input:visible").focus();					   
    	            },
    	           Cancel: function() {
    	               $( this ).dialog( "close" );
					   $(curr).closest("div").next().find("input:visible").focus();
    	           }
    	    }
    	});
    });*/
    
	$('.close').live("click",function(){
	   $('#successDiv').hide();
	   	
	});
	
	
});

$(".checkboxAllReim-QGL").live("click",function(){
    var checkval = $(this).is(":checked");
    $('.reimchecktype').each(function(index) {
    	if(!$(this).is(":disabled"))
    		$(this).attr("checked",checkval);
    });
});

$(".QGLAllcheckboxClass").live("click",function(){
		var checkval = $(this).is(":checked");
			$(".QGLcheckboxClass").each(function(){
			if(!$(this).is(":disabled"))
				$(this).attr("checked",checkval);
			});
	});

$(".checkboxAllTax-QGL").live("click",function(){
	 var checkval = $(this).is(":checked");
	 $('.taxchecktype').each(function(index) {
	    	if(!$(this).is(":disabled"))
	    		$(this).attr("checked",checkval);
	    });
});
var initialTypeId="";
function getInitialValue(elem){
	initialTypeId=$(elem).val();
	//console.log(initialTypeId);
}

function getChangedValue(elem){
	var changedVal=$(elem).val();
	if(initialTypeId=="" && changedVal!="")
		$(elem).trigger("change");
}
function saveSelectedJob(jobId,isCalcReq){
	
	var flag =false;
	var estPgs = $("#estPgs"+jobId).val();
	var ccVal = $("#ccVal"+jobId).val();
	var scActulPgs = $("#scActulPgs"+jobId).val();
	var prActulPgs = $("#prActulPgs"+jobId).val();
	var actulPgs = $("#actulPgs"+jobId).val();
	
	if(actulPgs == 0){
		$("#actulPgs"+jobId).val(1)
		actulPgs = 1;
	}
		
	var scopistHrs = $("#scopistHrs"+jobId).val();
	var prooferHrs = $("#prooferHrs"+jobId).val();
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Numeric Value.</li></ul><span></span></div></div>';
	 if(isNaN(actulPgs))
	{
		$('.numberval').before(numbererrorstr);
	
		flag =true;
	}
	else if(actulPgs % 1 != 0)
	{
		$('.numberval').before(numbererrorstr);
	
		flag =true;
	}
	if(isNaN(estPgs))
	{
		$('.numberval').before(numbererrorstr);
	
		flag =true;
	}
	else if(estPgs % 1 != 0)
	{
		$('.numberval').before(numbererrorstr);
	
		flag =true;
	}
	else if(isNaN(ccVal))
	{
		$(".numberval").before(numbererrorstr);
		flag =true;	
	}
	else if(ccVal % 1 != 0)
	{
		$('.numberval').before(numbererrorstr);
	
		flag =true;
	}

	else if(isNaN(scActulPgs))
	{
		$('.numberval').before(numbererrorstr);
	
		flag =true;
	}
	else if(scActulPgs % 1 != 0)
	{
		$('.numberval').before(numbererrorstr);
	
		flag =true;
	}
	if(isNaN(prActulPgs))
	{
		$('.numberval').before(numbererrorstr);
	
		flag =true;
	}
	else if(prActulPgs % 1 != 0)
	{
		$('.numberval').before(numbererrorstr);
	
		flag =true;
	}
	/*else if(isNaN(scopistHrs))
	{
		$(".numberValForDecimal").before(numbererrorstr);
		flag =true;

	}
	else if(isNaN(prooferHrs))
	{
		$(".numberValForDecimal").before(numbererrorstr);
		flag =true;
	}*/
	
	if(flag)
	return;
	
	if(!flag){
	$('.numberval').parent().find(".ketchup-errorPar").remove();
	//$(".numberValForDecimal").parent().find(".ketchup-errorPar").remove();

	var jobData={
	 jobId : $("#jobId"+jobId).val(),
	 agencyId : $("#agencyId"+jobId).val(),
	 dateTaken : $("#dateTaken"+jobId).val(),
	 estPgs : $("#estPgs"+jobId).val(),
	 scopistId : $("#scopistId"+jobId).val(),
	 scopistName : $("#scopistName"+jobId).val(),
	 prooferId : $("#prooferId"+jobId).val(),
	 prooferName : $("#prooferName"+jobId).val(),
	 caseName : $("#caseName"+jobId).val(),
	 scopistHrs : $("#scopistHrs"+jobId).val(),
	 prooferHrs : $("#prooferHrs"+jobId).val(),
	 dueAgenctDt : $("#dueAgenctDt"+jobId).val(),
	 totalHrs : $("#totalHrs"+jobId).val(),
	 typeId : $("#typeId"+jobId).val(),
	 jobReqId : $("#jobReqId"+jobId).val(),
	 actulPgs : $("#actulPgs"+jobId).val(),
	 scopistTo : $("#scopistTo"+jobId).val(),
	 scopistFrom : $("#scopistFrom"+jobId).val(),
	 prooferTo : $("#prooferTo"+jobId).val(),
	 prooferFrom : $("#prooferFrom"+jobId).val(),
	 witness : $("#witness"+jobId).val(),
	 scActulPgs : $("#scActulPgs"+jobId).val(),
	 prActulPgs : $("#prActulPgs"+jobId).val(),
	 dueAuttyDt : $("#dueAuttyDt"+jobId).val(),
	 hrsToDo : $("#hrsToDo"+jobId).val(),
	 ccVal : $("#ccVal"+jobId).val(),
	 //dateRec : $("#dateRec"+jobId).val(),
	 //dateDeliv : $("#dateDeliv"+jobId).val(),
	 servicesReim : $("#servicesReim"+jobId).val(),
	 expenNonReim : $("#expenNonReim"+jobId).val(),
	 notes : $("#notes"+jobId).val(),
	 actulTurnIn : $("#actulTurnIn"+jobId).val(),
	 statusId : $("#statusId"+jobId).val(),
	 scopistRateId : $("#scopistRateId"+jobId).val(),
	 prooferRateId : $("#prooferRateId"+jobId).val()
 }
    
    

	   $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?saveAjaxData',//name of action?name of method in action
		  dataType: 'json',
		  data: {jobData:JSON.stringify(jobData)},
			 
		  success: function(result){
			 if(isCalcReq)
				  callAjaxToCalculatePaymentAferJobSaving(jobId);


		 },
		  error:function() { 
			  
		  }
	});
	
}
	
}

  
  function getNewRateItemRow(result,typ,agtypeid,jobId,agencyId){
	     var actualPgs = $("#actulPgs"+jobId).val();
         var str ="";
		  str += " <tr id='a"+rateitemcount+"' class='rateitemclass'>";
          str += "<input type='hidden' class='disabled-background reimjobrateitemid' disabled='disabled' id='jobrateitemida"+rateitemcount+"' value='"+result.rateItemId+"' /></td>";
          
          if(result.rateItemId == agtypeid)
  	        str += "<td align='left' valign='middle'><input disabled='disabled' type='checkbox' class='disabled-background checkboxReim-QGL reimjobrateitemselected QGLcheckboxClass' id='jobrateitemselecteda"+rateitemcount+"' /></td>";
          else if(result.jobRateItem)
	        str += "<td align='left' valign='middle'><input type='checkbox' class='checkboxReim-QGL reimjobrateitemselected QGLcheckboxClass' id='jobrateitemselecteda"+rateitemcount+"'  checked='true'/></td>";
          else
          str += "<td align='left' valign='middle'><input type='checkbox' class='checkboxReim-QGL reimjobrateitemselected QGLcheckboxClass' id='jobrateitemselecteda"+rateitemcount+"' /></td>";
         
          
         if(result.rateItemId == agtypeid)
        	 str += "<td align='left' valign='middle'><input disabled='disabled' type='text'  class='disabled-background reimjobrateitemcode' id='jobrateitemcodea"+rateitemcount+"' value='"+result.codeName+"' style='background:#DDDDDD;color:black;' /></td>";
         else
          str += "<td align='left' valign='middle'><input type='text'  class='reimjobrateitemcode' id='jobrateitemcodea"+rateitemcount+"' value='"+result.codeName+"' /></td>";
        
         
         if(result.rateItemId == agtypeid)
        	 str += "<td align='left' valign='middle'><input type='text' disabled='disabled'  class='disabled-background reimjobrateitemdesc' id='jobrateitemdesca"+rateitemcount+"' value='"+result.rateItemDescription+"'  style='background:#DDDDDD;color:black;'/></td>";
         else
         str += "<td align='left' valign='middle'><input type='text'  class='reimjobrateitemdesc' id='jobrateitemdesca"+rateitemcount+"' value='"+result.rateItemDescription+"' /></td>";
		 
         if(result.rateItemId == agtypeid)
        	 str += "<td align='left' valign='middle'><input type='text' disabled='disabled'  class='textboxwidthdet disabled-background reimjobrateitemquantity' id='jobrateitemquantitya"+rateitemcount+"' value='1.00'  style='background:#DDDDDD;color:black;'/></td>";
         else
             str += "<td align='left' valign='middle'><input type='text'  class='textboxwidthdet reimjobrateitemquantity' id='jobrateitemquantitya"+rateitemcount+"' value='"+result.quantity.toFixed(2)+"' /></td>";
		 
         
         if(agtypeid == result.rateItemId)
			  str += "<td align='left' valign='middle'><input type='text' class='disabled-background textboxwidthdet reimjobrateitemcount' disabled='disabled' id='jobrateitemcounta"+rateitemcount+"' value='"+actualPgs+"' style='background:#DDDDDD;color:black;'/></td>";
		  else if(typ != "new" && typ != "master" )
		   str += "<td align='left' valign='middle'><input type='text' class='textboxwidthdet reimjobrateitemcount' id='jobrateitemcounta"+rateitemcount+"' value='1.00' /></td>";
		  else 
			   str += "<td align='left' valign='middle'><input type='text' class='textboxwidthdet reimjobrateitemcount' id='jobrateitemcounta"+rateitemcount+"' value='"+result.value.toFixed(2)+"' /></td>";
		  
         
         if(typ != "new" || typ == "master" )
           str += "<td align='left' valign='middle'><input type='text' class='textboxwidthdet reimjobrateitemprice'  id='jobrateitempricea"+rateitemcount+"' value='"+result.rateItemValue+"' /></td>";
		  else
			  str += "<td align='left' valign='middle'><input type='text'  class='textboxwidthdet reimjobrateitemprice' id='jobrateitempricea"+rateitemcount+"' value='"+result.rateItemPrice.toFixed(2)+"' /></td>";  
		  
         
         if(agtypeid == result.rateItemId)
			  str +="<td align='left' valign='middle'><select disabled='disabled' class='disabled-background reimjobrateitemrateunit' onchange='changeoptions(\"jobrateitemrateunita"+rateitemcount+"\",\"jobrateitemperunita"+rateitemcount+"\");'  id='jobrateitemrateunita"+rateitemcount+"'>";
		  else
			  str +="<td align='left' valign='middle'><select class='reimjobrateitemrateunit' onchange='changeoptions(\"jobrateitemrateunita"+rateitemcount+"\",\"jobrateitemperunita"+rateitemcount+"\");'  id='jobrateitemrateunita"+rateitemcount+"'>";
		 
          for(var j = 0; j< rateunits.length ; j++){
        	
        	if(result.priceType != rateunits[j].id)  
             str +="<option value='"+rateunits[j].id+"'>"+rateunits[j].type+"</option>";
			else
			 str +="<option value='"+rateunits[j].id+"' selected='selected'>"+rateunits[j].type+"</option>";
          }
		  str +="</select></td>";
		  
		  
		  if(agtypeid == result.rateItemId)
			  str +="<td align='left' valign='middle'><select disabled='disabled' class='disabled-background reimjobrateitemperunit' id='jobrateitemperunita"+rateitemcount+"' style='width:72px;'>";
		  else
		     str +="<td align='left' valign='middle'><select class='reimjobrateitemperunit' id='jobrateitemperunita"+rateitemcount+"' style='width:72px;'>";
		  
		  for(var j = 0; j< rateunits.length ; j++){
			if(result.priceType == rateunits[j].id){
				if(rateunits[j].type == "%"){
					   for(var k = 0 ; k < reqrtcodes.length ; k++){
		                   if(result.unitType != reqrtcodes[k].rateItemId)  
		                    str +="<option value='"+reqrtcodes[k].rateItemId+"'>"+reqrtcodes[k].codeName+"</option>";
					       else
					        str +="<option value='"+reqrtcodes[k].rateItemId+"' selected='selected'>"+reqrtcodes[k].codeName+"</option>";
		                 }	
				}
				else{
                  for(var k = 0 ; k < perrateunits.length ; k++){
                   if(result.unitType != perrateunits[k].id)  
                    str +="<option value='"+perrateunits[k].id+"'>"+perrateunits[k].type+"</option>";
			       else
			        str +="<option value='"+perrateunits[k].id+"' selected='selected'>"+perrateunits[k].type+"</option>";
                 }
               }
			}
		  }
		  str +="</select></td>";
		 
		  
		 if(result.reimbursable == true )
          str += "<td align='center' valign='middle'><input class='reimchecktype' type='checkbox' checked='true'  id='jobrateitemreimba"+rateitemcount+"' /></td>";
         else
        	 str += "<td align='center' valign='middle'><input class='reimchecktype' type='checkbox'  id='jobrateitemreimba"+rateitemcount+"' /></td>";	 
         
		 
		 if(result.taxable == true)
            str += "<td align='center' valign='middle'><input class='taxchecktype' type='checkbox'  checked='true' id='jobrateitemtaxabla"+rateitemcount+"' /></td>";
         else
        	 str += "<td align='center' valign='middle'><input class='taxchecktype' type='checkbox' id='jobrateitemtaxabla"+rateitemcount+"' /></td>";
        
		 var delid = "a"+rateitemcount;
         
		 if(typ == "master")
            str += "<td align='left' valign='middle'><input class='servdelete' type='button' value='Delete' onclick='deleteSelectedRow(\""+delid+"\")' style='cursor:pointer;'></input></td>";
          else
        	 str += "<td align='left' valign='middle'><input class='servdelete' type='button' value='Delete' onclick='deleteSelectedRateItem(\""+delid+"\","+jobId+","+agencyId+","+result.rateItemId+")' style='cursor:pointer;'></input></td>"; 
        
		 str += "</tr>";
         rateitemcount++;
	  return str;
  }
  
  
  function deleteSelectedRow(reqid){
	  $("#allservicreimErrorMSGdiv").html("");
	  $("#allservicreimErrorMSGdivOuter").html("");
	  var code= $("#"+reqid).find(".reimjobrateitemcode").val();
	  var flag=false;
	  $("#"+reqid).siblings().each(function(){
	     if($(this).find(".reimjobrateitemperunit").find('option:selected').text()==code){flag=true;}
	  });
	  if(flag){
	  
	   $("#allservicreimErrorMSGdiv").html(code+" is used as expedite Per Unit").addClass("errorblockdiv").show();
	   $("#allservicreimErrorMSGdivOuter").html(code+" is used as expedite Per Unit").addClass("errorblockdiv");
	 
	  }
	  else{
		var r=confirm("Do you want to delete?");
	  if (r==true)
	    { 
	      $('#'+reqid).remove();
	    } 
	  ServhighlightDuplicates(".reimjobrateitemcode");	
	  }
  }
  
  
   function deleteSelectedRateItem(reqid,jobId,agencyId,rtid){
	   $("#allservicreimErrorMSGdiv").html("");
	   $("#allservicreimErrorMSGdivOuter").html("");
	   var code= $("#"+reqid).find(".reimjobrateitemcode").val();
		  var flag=false;
		  $("#"+reqid).siblings().each(function(){
		     if($(this).find(".reimjobrateitemperunit").find('option:selected').text()==code){flag=true;}
		  });
		  if(flag){
		  
		   $("#allservicreimErrorMSGdiv").html("Rate item to be deleted has been applied as expedite. Please make sure that no dependency exists and then delete").addClass("errorblockdiv").show();
		   $("#allservicreimErrorMSGdivOuter").html("Rate item to be deleted has been applied as expedite. Please make sure that no dependency exists and then delete").addClass("errorblockdiv");
		   return false;
		  }
	  else{
	  var r=confirm("Do you want to delete?");
	  if (r==true){
		   $.ajaxSetup({
			   jsonp: null,
			   jsonpCallback: null
			});

		    $.ajax({
			  type:'POST',
			  url: 'rate-template.action?deleteRateItem',
			  dataType: 'json',
			  data: {jobId:jobId,agencyId:agencyId,rateItemId:rtid},
				 
			  success: function(result){
				if(result){ 
					$('#'+reqid).remove();
				}else{
					$("#allservicreimErrorMSGdiv").html("Selected Rate Code is used in other jobs, cannot be deleted.").addClass("errorblockdiv");
         			$("#allservicreimErrorMSGdivOuter").html("Selected Rate Code is used in other jobs, cannot be deleted.").addClass("errorblockdiv");
				}
				    
			 },
			  error:function() { 
				  
			  }
		 });
		  
       }
	  ServhighlightDuplicates(".reimjobrateitemcode");	
	  }
  }
  
  function addNewRowItem(type){
	         var str ="";
			  str += " <tr id='a"+rateitemcount+"' class='rateitemclass'>";
	          str += "<input type='hidden' class='reimjobrateitemid' id='jobrateitemida"+rateitemcount+"'value='0'  /></td>";
	          str += "<td align='left' valign='middle'><input type='checkbox'  id='jobrateitemselecteda"+rateitemcount+"' class='reimjobrateitemselected checkboxReim-QGL QGLcheckboxClass' /></td>";
	          str += "<td align='left' valign='middle'><input type='text' class='reimjobrateitemcode' id='jobrateitemcodea"+rateitemcount+"'  /></td>";
			  str += "<td align='left' valign='middle'><input type='text' class='reimjobrateitemdesc' id='jobrateitemdesca"+rateitemcount+"'  /></td>";
			  str += "<td align='left' valign='middle'><input type='text' class='reimjobrateitemquantity textboxwidthdet' id='jobrateitemquantitya"+rateitemcount+"' value='1.00'  /></td>";
			  str += "<td align='left' valign='middle'><input type='text' class='reimjobrateitemcount textboxwidthdet' id='jobrateitemcounta"+rateitemcount+"' value='1.00'  /></td>";
	          str += "<td align='left' valign='middle'><input type='text' class='reimjobrateitemprice textboxwidthdet' id='jobrateitempricea"+rateitemcount+"' value='0.00' /></td>";
			  str +="<td align='left' valign='middle'><select class='reimjobrateitemrateunit' id='jobrateitemrateunita"+rateitemcount+"' onchange='changeoptions(\"jobrateitemrateunita"+rateitemcount+"\",\"jobrateitemperunita"+rateitemcount+"\");'>";
	          for(var j = 0; j< rateunits.length ; j++){
	             str +="<option value='"+rateunits[j].id+"'>"+rateunits[j].type+"</option>";
	          }
			  str +="</select></td>";
			  str +="<td align='left' valign='middle'><select class='reimjobrateitemperunit' id='jobrateitemperunita"+rateitemcount+"' style='width:72px;'>";
	         for(var k = 0 ; k < perrateunits.length ; k++){
	             str +="<option value='"+perrateunits[k].id+"'>"+perrateunits[k].type+"</option>";
	         }
			  str +="</select></td>";
			  if(type == "reim")
	             str += "<td align='center' valign='middle' class='reimchecktype'><input type='checkbox'  id='jobrateitemreimba"+rateitemcount+"' class='checkboxReim-QGL reimchecktype' checked='true'/></td>";
			  else
				  str += "<td align='center' valign='middle' class='reimchecktype'><input type='checkbox'  id='jobrateitemreimba"+rateitemcount+"' class='checkboxReim-QGL reimchecktype' /></td>";	 
              str += "<td align='center' valign='middle'><input class='taxchecktype' type='checkbox' id='jobrateitemtaxabla"+rateitemcount+"' class='checkboxTax-QGL' /></td>";
              var delid = "a"+rateitemcount;
              str += "<td align='left' valign='middle'><input class='servdelete' type='button' value='Delete' onclick='deleteSelectedRow(\""+delid+"\")' style='cursor:pointer;'></input></td>";
	         str += "</tr>";
	         $('#servreimberstable > tbody:last').append(str);
	         rateitemcount++;
  }
  function changeoptions(unitid,perunitid){
	  $("#"+perunitid+" option").remove();
	  if($("#"+unitid+" option:selected").text() == "%"){
		  for(var k = 0 ; k < reqrtcodes.length ; k++){
			  $('#'+perunitid).append("<option value='"+reqrtcodes[k].rateItemId+"'>"+reqrtcodes[k].codeName+"</option>");
            }	  
		  
	  }
	  else{
		  for(var k = 0 ; k < perrateunits.length ; k++){ 
			  $('#'+perunitid).append("<option value='"+perrateunits[k].id+"'>"+perrateunits[k].type+"</option>");
		     
            }  
		  
	  }
  }
  function saveccvalue(jobData,ccobj, agencyId){
	  if(retflag) {
		$(".numberVal").QGLCustomValidatorNum("number",true,this);}
	  if(retflag)
		$(".numberValForDecimal").QGLCustomValidatorDeciNum("number",true,this);

		flag=retflag;
		if(flag)
		{
			var agencyId = $("#agencyId"+jobData).val();
			var actualPgs = $("#actulPgs"+jobData).val();
			if(!(actualPgs != null && $.trim(actualPgs).length > 0 && actualPgs > 0))
				actualPgs = 1;
			if(agencyId != null && $.trim(agencyId).length > 0 && agencyId > 0){
	  var ccVal = $("#ccVal"+jobData).val();
	   $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?saveCCValToJobService',//name of action?name of method in action
		  dataType: 'json',
		  data: {jobId:jobData,ccVal:ccVal, agencyId:agencyId,actualPgs:actualPgs},
			 
		  success: function(result){

		 },
		  error:function() { 
			  
		  }
	});
	}
  } 
  }
  
  function saveccvalueToJob(jobData,ccobj){
	 
	  var ccVal = document.getElementById(ccobj).value;
	   $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?saveCCValToJob',//name of action?name of method in action
		  dataType: 'json',
		  data: {jobId:jobData,ccVal:ccVal},
			 
		  success: function(result){

		 },
		  error:function() { 
			  
		  }
	});
	
 }


//Services Reiumbersed Detail Accounting Validate Duplicates.....
  function ServhighlightDuplicates(classname){
  var flag=false;
  $(classname).each(function(){
  $(this).closest("tr").removeClass("errorHighlight");
  $("#allservicreimErrorMSGdivOuter").html("").removeClass("errorblockdiv");
  $("#allservicreimErrorMSGdiv").html("").removeClass("errorblockdiv");
     var currentcode=$.trim($(this).val().toLowerCase()); 

  							$(this).closest("tr").siblings().find(".reimjobrateitemcode").each(function(){
  							var othercodes=$.trim($(this).val().toLowerCase()); 
  							if(othercodes==currentcode && currentcode!=""){
  							 flag=true;
  							  $(this).closest("tr").addClass("errorHighlight");
  							   $("#allservicreimErrorMSGdivOuter").html("This code already exists. Please choose from the master rate table or create a new code").addClass("errorblockdiv");
  							   $("#allservicreimErrorMSGdiv").html("This code already exists. Please choose from the master rate table or create a new code").addClass("errorblockdiv");
  							}
  							});
  							
  							
  							});
  return flag;
  }	

  function  serviceAutoPopulateMRItem(idfield,type)
  {
       var itemval=$.trim($(idfield).val().toLowerCase());
 	 
 	  for (var i=0;i<resultset.length;i++)
 	   {
 	     if($.trim(resultset[i].codeName).toLowerCase()==itemval)
 		 {
 		     $(idfield).closest("tr").find(".masterrateitemchecked").attr('checked','checked');

 		     $(idfield).closest("tr").find(".reimjobrateitemdesc").val(resultset[i].userRateItemDescription);
 			
      		 $(idfield).closest("tr").find(".reimjobrateitemcount").val(1.00);
 			 $(idfield).closest("tr").find(".reimjobrateitemprice").val(1.00);
 			
 			 $(idfield).closest("tr").find(".reimjobrateitemrateunit").val(resultset[i].unit);
 			 changeoptions($(idfield).closest("tr").find(".reimjobrateitemrateunit").attr("id"),$(idfield).closest("tr").find(".reimjobrateitemperunit").attr("id"));
 			 $(idfield).closest("tr").find(".reimjobrateitemperunit").val(resultset[i].perUnit);   
 			 $(idfield).closest("tr").find(".reimchecktype").attr('checked',resultset[i].reimbursble);
 			 $(idfield).closest("tr").find(".taxchecktype").attr('checked',resultset[i].taxable);
 			   
 		 }
 	   }
  }

  function servicesReimexpedite(){
	  $(".rateitemclass").each(function(){

	  var perunitid=$(this).find(".reimjobrateitemperunit");
	  var unitid=$(this).find(".reimjobrateitemrateunit");

	  if($(unitid).val()==2){
	  var newRateItemsList=[];
	  // building all codes list from all the rows
	   $(this).siblings().find(".reimjobrateitemcode").each(function(){
	   
	     if($(this).closest("tr").find(".reimjobrateitemrateunit").val()!=2){

	  			     	 var newRateItemCode=$.trim($(this).val());
	  					 var newRowIdx=$(this).attr("id").split("codea");
	  					 if(newRateItemCode!=""){
	  					       var newRtItem={
	  							id: -newRowIdx[1]-1,
	  							type: newRateItemCode }
						 
	  			    	 newRateItemsList.push(newRtItem); } }
	   });
	  // Change the ids of already existed codes.
	  for (var i in newRateItemsList){
	     
	     for (var j in reqrtcodes){
	       if($.trim(newRateItemsList[i].type.toLowerCase())==$.trim(reqrtcodes[j].codeName.toLowerCase())) {newRateItemsList[i].id=reqrtcodes[j].rateItemId;}
	     }
	   }
	   //Then for each of the values of the array, append those values into the existing select "my_states" dropdown
	   var selectedval=$(perunitid).val();
	   $(perunitid).empty();
	  for (var i in newRateItemsList){
	   $(perunitid)
	   .append($('<option>', { value : newRateItemsList[i].id })
	   .text(newRateItemsList[i].type));
	  };
	   $(perunitid).val(selectedval); 
	   } // end of % selection condition
	   }); // end of tbody loop
	 }
  
  function caluculateAllHours(jobid){
	  var estimatedPages = 0;
	  var scopistId = 0;
	  var prooferId = 0;
	  if($.trim($("#estPgs"+jobid).val()).length > 0 && $("#estPgs"+jobid).val() > 0)
		  estimatedPages = $("#estPgs"+jobid).val();
	  
	  if($.trim($("#scopistId"+jobid).val()).length > 0 && $("#scopistId"+jobid).val() > 0)
		  scopistId = $("#scopistId"+jobid).val();
	  
	  if($.trim($("#prooferId"+jobid).val()).length > 0 && $("#prooferId"+jobid).val() > 0)
		  prooferId = $("#prooferId"+jobid).val();
	  
	  calculateHrsToDoAndTotalHrs(estimatedPages,jobid,scopistId,prooferId);
  }
  
  function calculateHrsToDoAndTotalHrs(estimatedPages,jobId,scopistId,prooferId){
	   $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?calculateHrsToDoAndTotalHrs',//name of action?name of method in action
		  dataType: 'json',
		  data: {jobId:jobId,estPages:estimatedPages,scopistId:scopistId,prooferId:prooferId},
			 
		  success: function(result){
          if(result != null){
        	  
        	  $("#hrsToDo"+jobId).val(result.toDoHours);
        	  $("#totalHrs"+jobId).val(result.totalHours);
        	  if(result.scopistValReq)
        	    $("#scopistHrs"+jobId).val(result.scopistHours);
        	  else
        		$("#scopistHrs"+jobId).val("");
        	  if(result.prooferValReq)
        	    $("#prooferHrs"+jobId).val(result.prooferHours);
        	  else
        		  $("#prooferHrs"+jobId).val("");
          }
		 },
		  error:function() { 
			  
		  }
	});
	
 }
 function decimalNumbervalidtion(eleVal){
			var flag=true;
			if(isNaN(eleVal))
				flag =false;
			return flag;
		}
	function saveAdminstrativeHoursInJob(actualUserId,jobId){
	var str ='';	 
	var flag = true;
	var errmsg = $('#errorDiv');
	var skillAdminHrs = $('#skillAdminHrsId').val();
	//var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Numeric Value.</li></ul></div></div>';
	var defaultSkillType = $('input[name=hrstodoname]:radio:checked').val();
	var flag= decimalNumbervalidtion(skillAdminHrs);
	if(!flag)
	{
		//$('.decimalnumberVal').before(numbererrorstr);
		$('#errorDiv').text("Enter Numeric Value.").addClass( "ui-state-highlight").css({"background":"#FFE4DD", "margin-bottom": "5px", "width": "250px", "padding": "3px", "font-family": "verdana","font-weight": "bold","color":"#000"});
    
		
		return;
	}
	if(flag)
		  {
$("#errorDiv").empty();
			$("#errorDiv").removeClass("errdiv");
 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-pending.action?saveAdminstrativeHoursInJob',
		  dataType: 'json',
		  data: {userId:actualUserId, jobId:jobId,skillAdminHrs:skillAdminHrs,defaultSkillType:defaultSkillType},
			 
		  success: function(result){
			  
					$('#errorDiv').text("Administrative Hours saved Successfully").addClass("alert alert-success");
			$('.estimatePages').closest("div").next().find("input:visible").focus();
					setTimeout("closewindow()",2000);
				  caluculateAllHours(jobId);
			           
		  },
		  error:function() { 
			  
		  }
 	});	
		  }
}

function closewindow()
{
	$("#estimatePages-form").dialog("destroy");
}

function callAjaxToDisplayAdminstrativeHours(actualUserId,jobId){	
	
	 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-pending.action?checkIfHoursToPerFormExist',
		  dataType: 'json',
		  data: {userId:actualUserId, jobId:jobId},
			 
		  success: function(result){
			  if(result!=null){
				 //showError(userType, agency);
				//quiggleJobAutoComplete(result, '.est-id',"#estimatePages-form");
				showDialogue(result);
			  }            
		  },
		  error:function() { 
			  
		  }
 	});	
	
}

function showDialogue(result)
{
	
	var str='';
	str +='<div id="errorDiv"></div>';
	 str+=' <fieldset>'
     str+=' <div style="font-size: 14px;font-family: verdana;">';
     str+='<input type="hidden" name="block-id" class="block-id" value=""/>';
     for(var i=0;i<result.length;i++)
	{ 
		 if(result[i].defaultSkillType == 1)
		{
			 str +='<div id="regularDefaultDiv" class="selectedTask">';
    str+='<input type="radio" name="hrstodoname"  class="hrstodoname" id="regularDefault" value="1" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;" checked="true"/>';
		}
		else
		{
			 str +='<div id="regularDefaultDiv">';
			str+='<input type="radio" name="hrstodoname"  class="hrstodoname" id="regularDefault" value="1" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;"/>';
		}

	str+=' <span class="label">Regular</span>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">';
	str +='<span>Scope</span>';
	str+='<span style="padding-left:5px;">'+result[i].regularScopeHours+'</span>';
	str +='</div>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">';
	str +='<span>Proof</span>';
	str+='<span style="padding-left:5px;">'+result[i].regularProofHours+'</span>';
	str +='</div>';
	str +='</div>';
	str +='<br>';
	 if(result[i].defaultSkillType == 2)
		{
		  str +='<div id="denseDefaultDiv" class="selectedTask">';
		 str+=' <input type="radio" name="hrstodoname" class="hrstodoname"  id="denseDefault" value="2" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;" checked="true"/>';
		}
		else
		{
			 str +='<div id="denseDefaultDiv">';
str+=' <input type="radio" name="hrstodoname"  class="hrstodoname" id="denseDefault" value="2" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;"/>';
		}
	str+=' <span class="label">Dense</span>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">';
	str +='<span>Scope</span>';
	str+='<span style="padding-left:5px;">'+result[i].denseScopeHours+'</span>';
	str +='</div>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">'
	str +='<span>Proof</span>';
	str+='<span style="padding-left:5px;">'+result[i].denseProofHours+'</span>';
	str +='</div>';
	str +='</div>';
	str +='<br>';
	
	 if(result[i].defaultSkillType == 3)
		{
		str +='<div id="easyDefaultDiv" class="selectedTask">';
    str+=' <input type="radio" name="hrstodoname" class="hrstodoname"  id="easyDefault" value="3" class="initial text ui-widget-content ui-corner-all" style="margin-left:4px;" checked="true"/>';
	 
		}
		else
		{
			 str +='<div id="easyDefaultDiv">';
	str+=' <input type="radio" name="hrstodoname" class="hrstodoname"  id="easyDefault" value="3" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;"/>';
		}
	str+=' <span class="label">Easy</span>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">'
	str +='<span>Scope</span>';
	str+='<span style="padding-left:5px;">'+result[i].easyScopeHours+'</span>';
	str +='</div>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">'
	str +='<span>Proof</span>';
	str+='<span style="padding-left:5px;">'+result[i].easyProofHours+'</span>';
	str +='</div>';
	str +='</div>';
	str +='<br><br>';
	str +='<div style="font-size:11px;">(To change the values of default fields above, please do so from your Profile page.)</div><br>';
	str +='<div style="font-size:12px;">';
	str+=' <label for="skillAdminHrs">FOR THIS PARTICULAR JOB: Administrative Hours</label>';
	str+='<input type="text" maxlength="10" id="skillAdminHrsId" value="'+result[i].administrativeHours+'" name="skillAdminHr" style="width:60px;height:18px;border-radius: 3px 3px 3px 3px;border:1px solid #ccc;margin-left:1px;padding:3px;display: inline-table;" class="decimalnumberVal skillAdminHrs"/>';
	str +='</div>';
	}
	str+='</div>';
    str+=' </fieldset>';
	$("#estimatePages-formInnerDiv").html(str);
      
}

